import React, { Component } from 'react';
import logo from "../../../img1/logo.png";
import wx from "../../../img1/wx.png";
import qq from "../../../img1/qq.png";
import axios from '../../../axios/axios'
import {Link } from 'react-router-dom'
import Foot from '../../components3/foot/foot'
import {
    CheckCircleOutlined,
    ExclamationCircleFilled,
    UserOutlined
} from '@ant-design/icons';
import { Button,message } from 'antd';
class loginyzm extends Component {
    constructor(props) {
        super(props);     //继承关键字
        this.state = {
            phone: "",
            pwd: '',
            yzm: '',
            autologin:false,
            jiancha:false,
            code: '',
            codeLength: 4,
            fontSizeMin: 20,
            fontSizeMax: 22,
            backgroundColorMin: 240,
            backgroundColorMax: 250,
            colorMin: 10,
            colorMax: 20,
            lineColorMin: 40,
            lineColorMax: 180,
            contentWidth: 96,
            contentHeight: 38,
            showError: false, // 默认不显示验证码的错误信息
        };
    }
//验证码
componentWillMount() {
    this.canvas = React.createRef()
}

componentDidMount() {
    this.drawPic()
}
 // 生成一个随机数
// eslint-disable-next-line arrow-body-style
randomNum = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min)
}

drawPic = () => {
    this.randomCode()
}

// 生成一个随机的颜色
// eslint-disable-next-line react/sort-comp
randomColor(min, max) {
    const r = this.randomNum(min, max)
    const g = this.randomNum(min, max)
    const b = this.randomNum(min, max)
    return `rgb(${r}, ${g}, ${b})`
}

drawText(ctx, txt, i) {
    ctx.fillStyle = this.randomColor(this.state.colorMin, this.state.colorMax)
    const fontSize = this.randomNum(this.state.fontSizeMin, this.state.fontSizeMax)
    ctx.font = fontSize + 'px SimHei'
    const padding = 10;
    const offset = (this.state.contentWidth - 40) / (this.state.code.length - 1)
    let x = padding;
    if (i > 0) {
        x = padding + (i * offset)
    }
    let y = this.randomNum(this.state.fontSizeMax, this.state.contentHeight - 5)
    if (fontSize > 40) {
        y = 40
    }
    const deg = this.randomNum(-10, 10)
    // 修改坐标原点和旋转角度
    ctx.translate(x, y)
    ctx.rotate(deg * Math.PI / 180)
    ctx.fillText(txt, 0, 0)
    // 恢复坐标原点和旋转角度
    ctx.rotate(-deg * Math.PI / 180)
    ctx.translate(-x, -y)
}

drawLine(ctx) {
    // 绘制干扰线
    for (let i = 0; i < 1; i++) {
        ctx.strokeStyle = this.randomColor(this.state.lineColorMin, this.state.lineColorMax)
        ctx.beginPath()
        ctx.moveTo(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight))
        ctx.lineTo(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight))
        ctx.stroke()
    }
}

drawDot(ctx) {
    // 绘制干扰点
    for (let i = 0; i < 100; i++) {
        ctx.fillStyle = this.randomColor(0, 255)
        ctx.beginPath()
        ctx.arc(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight), 1, 0, 2 * Math.PI)
        ctx.fill()
    }
}

reloadPic = (e) => {
    this.drawPic();
    e.preventDefault()
    console.log(this.state.code)
    // this.props.form.setFieldsValue({
    //     sendcode: '',
    // });
}

// 输入验证码
changeCode = e => {
    if (e.target.value.toLowerCase() !== '' && e.target.value.toLowerCase() !== this.state.code.toLowerCase()) {
        this.setState({
            showError: true
        })
    } else if (e.target.value.toLowerCase() === '') {
        this.setState({
            showError: false
        })
    } else if (e.target.value.toLowerCase() === this.state.code.toLowerCase()) {
        this.setState({
            showError: false
        })
    }
}

// 随机生成验证码
randomCode() {
    let random = ''
    // 去掉了I l i o O,可自行添加
    const str = 'QWERTYUPLKJHGFDSAZXCVBNMqwertyupkjhgfdsazxcvbnm1234567890'
    for (let i = 0; i < this.state.codeLength; i++) {
        const index = Math.floor(Math.random() * 57);
        random += str[index];
    }
    this.setState({
        code: random
    }, () => {
        const canvas = this.canvas.current;
        const ctx = canvas.getContext('2d')
        ctx.textBaseline = 'bottom'
        // 绘制背景
        ctx.fillStyle = this.randomColor(this.state.backgroundColorMin, this.state.backgroundColorMax)
        ctx.fillRect(0, 0, this.state.contentWidth, this.state.contentHeight)
        // 绘制文字
        for (let i = 0; i < this.state.code.length; i++) {
            this.drawText(ctx, this.state.code[i], i)
        }
        this.drawLine(ctx)
        this.drawDot(ctx)
    })
}

    change(e) {
        // console.log(e.target.name);    //获取修改后的值
        if(e.target.name==='phone'){
            this.setState({
                phone: e.target.value
            })
        }else if(e.target.name==='pwd'){
            this.setState({
                pwd: e.target.value
            })
        }else if(e.target.name==='yzm'){
            this.setState({
                yzm: e.target.value
            })
        }else if(e.target.name==='auto'){
            // console.log(e.target.checked)
            this.setState({
                autologin: e.target.checked
            })
        }
        
    }
    jiancha(e){
        if(e.target.name==='phone'){
      if (!/^1[3456789]\d{9}$/.test(this.state.phone)) {
        this.setState({
            jiancha: false
        })
        e.target.parentNode.classList.add('error');
        e.target.parentNode.classList.remove('ok');
        // e.target.nextElementSibling.
    }else{
        this.setState({
            jiancha: true
        })
        e.target.parentNode.classList.remove('error');
        e.target.parentNode.classList.add('ok');
      }
        }else if(e.target.name==='pwd'){
            if (this.state.pwd.length<6) {
                this.setState({
                    jiancha: false
                })
                e.target.parentNode.classList.add('error');
                e.target.parentNode.classList.remove('ok');
                // e.target.nextElementSibling.
            }else{
                this.setState({
                    jiancha: true
                })
                e.target.parentNode.classList.remove('error');
                e.target.parentNode.classList.add('ok');
              }
        }
    }
    // 登录
    login(){
        if(this.refs.yzm.value!==this.state.code){
            this.refs.yzm.parentNode.classList.add('error');
            this.refs.yzm.parentNode.classList.remove('ok');
        }else{
            console.log(this.state.jiancha)
        if(this.state.jiancha){
            axios.post("small/user/v1/login", {
                phone: this.state.phone,
                pwd: this.state.pwd,
              })
              .then((res) => {
                console.log(res);
                if (res.data.status == "1001") {
                  // 失败
                  message.error(res.data.message);
                } else if (res.data.status == "0000") {
                  // 成功
                  message.success(res.data.message);
                  if(this.state.autologin){
                    window.localStorage.setItem(
                        "user_info",
                        JSON.stringify(res.data.result)
                      );
                  }
                }
              });
        }
        
        }
        
    }
    reg(){
        this.props.history.push('/register');
    }
    render() {
        return (
            <div className="main-banner">
                <div className="contain">
				<div className="center1">
					<Link to="/jingxuan"  target='_self'>欢迎光临易和生活港</Link><div className="line"></div><Link to="/login"  target='_self'>我是商家</Link><div className="line"></div><span>400-100-0907</span>
				</div>
			</div>
                <div className="main-banner-t container">
                    <img src={logo} alt="" />
                    <span>会员登录</span>
                </div>
                <div className="loginmima-main-banner-b">
                    <div className="main-banner-b-reg">
                        <div>
                            <div>
                                <strong>登录</strong>
                                
                                <Link to='/loginmima'>账户密码登录&nbsp;<UserOutlined /></Link>
                            </div>
                            <div><input onBlur={(event) => { this.jiancha(event) }} name="phone" value={this.state.phone} onInput={(event) => { this.change(event) }} placeholder="请输入手机号" type="text" />
                                <CheckCircleOutlined />
                                <div><ExclamationCircleFilled />&nbsp;&nbsp;手机号码不正确，请重新输入</div>
                            </div>
                            <div><input onBlur={(event) => { this.jiancha(event) }} name="pwd" value={this.state.pwd} onInput={(event) => { this.change(event) }} placeholder="请输入密码（6-20位号码字符）" type="password" />
                                <CheckCircleOutlined />
                                <div><ExclamationCircleFilled />&nbsp;&nbsp;密码不能小于6位，请重新输入</div></div>
                            <div><input ref="yzm" name="yzm" onInput={(event) => { this.change(event) }} value={this.state.yzm} placeholder="验证码" type="text" />
                                <div><ExclamationCircleFilled />&nbsp;&nbsp;验证码错误</div><canvas
                     ref={this.canvas}
                     width='79'
                     height='34'>
                 </canvas><a href="###"
                     onClick={(evevt)=>{this.reloadPic(event)}}>看不清楚换一张</a></div>
                                <div>
                                    <label><input name="auto" onChange={(event) => { this.change(event) }} type="checkbox" />自动登录</label>
                                    <a href="###">忘记密码？</a>
                                </div>
                            
                            <button onClick={this.login.bind(this)}>登录</button><button onClick={this.reg.bind(this)}>会员注册</button>
                            <div>
                                <p>用合作网站登录</p>
                                <img src={wx} alt=""/>
                                <img src={qq} alt=""/>
                            </div>
                        </div>
                    </div>
                </div>
                <Foot/>
            </div>
        );
    }
}

export default loginyzm;